//
//  AppDelegate.m
//  DMGME
//
//  Created by ihope99 on 15/8/27.
//  Copyright (c) 2015年 GYP. All rights reserved.
//
#import <RongIMKit/RongIMKit.h>
#import "AppDelegate.h"
#import "DMHomeViewController.h"
#import "DMLogInController.h"
#import "APService.h"
#import "MobClick.h"
#import <UMSocialCore/UMSocialCore.h>


//DW5Nwxn25xdvjopoUGvGQlwe

//融云开发环境下：App Key
//c9kqb3rdk5zzj
//App Secret
//RCJ7e4z5K8
//融云账号：app@dongmango.com    密码：dongmango2015
//1zjd4zGL6EnYlRNqLKRzoyYf

@interface AppDelegate ()

@end

@implementation AppDelegate
{
    BMKMapManager* _mapManager;

}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // 1.创建窗口
    self.window = [[UIWindow alloc] init];
    self.window.frame = [UIScreen mainScreen].bounds;
    [self.window makeKeyAndVisible];
    
    //融云
    [[RCIM sharedRCIM] initWithAppKey:@"c9kqb3rdk5zzj" ];
    [[RCIM sharedRCIM] setGroupInfoDataSource:self];
    // 设置用户信息提供者。
    [[RCIM sharedRCIM] setUserInfoDataSource:self];
    //设置会话列表头像和会话界面头像
    
    [[RCIM sharedRCIM] setConnectionStatusDelegate:self];

#ifdef __IPHONE_8_0
    // 在 iOS 8 下注册苹果推送，申请推送权限。
//    UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeBadge |UIUserNotificationTypeSound |UIUserNotificationTypeAlert) categories:nil];
//    [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
#else
    // 注册苹果推送，申请推送权限。
    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound];
#endif
 
    /**
     * 推送处理1
     */
    if ([application
         respondsToSelector:@selector(registerUserNotificationSettings:)]) {
        UIUserNotificationSettings *settings = [UIUserNotificationSettings
                                                settingsForTypes:(UIUserNotificationTypeBadge |
                                                                  UIUserNotificationTypeSound |
                                                                  UIUserNotificationTypeAlert)
                                                categories:nil];
        [application registerUserNotificationSettings:settings];
    } else {
        UIRemoteNotificationType myTypes = UIRemoteNotificationTypeBadge |
        UIRemoteNotificationTypeAlert |
        UIRemoteNotificationTypeSound;
        [application registerForRemoteNotificationTypes:myTypes];
    }
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(conectRongYunServer) name:@"Login" object:nil];
//       [[NSNotificationCenter defaultCenter] removeObserver:[NSNotificationCenter defaultCenter] name:nil object:self];
    if ([kkStatus isEqualToString:@"1"]) {
        // 2.设置窗口的根控制器
        DMHomeViewController *dmHomeVC = [[DMHomeViewController alloc] init];
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:dmHomeVC];
        self.window.rootViewController = nav;
    }else {
    // 2.设置窗口的根控制器
    DMLogInController *dmHomeVC = [[DMLogInController alloc] init];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:dmHomeVC];
    self.window.rootViewController = nav;
    }
    
    //百度地图
    _mapManager = [[BMKMapManager alloc]init];

    BOOL ret = [_mapManager start:@"DW5Nwxn25xdvjopoUGvGQlwe" generalDelegate:self];
    if (!ret) {
//        NSLog(@"manager start failed!");
    }
    
    [self conectRongYunServer];
    
    //极光推送
#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_7_1
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        //categories
        [APService
         registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |UIUserNotificationTypeSound |
                                             UIUserNotificationTypeAlert)
         categories:nil];
    }else {
        //categories nil
        [APService
         registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound |
                                             UIRemoteNotificationTypeAlert)
#else
         //categories nil
         categories:nil];
        [APService
         registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
                                             UIRemoteNotificationTypeSound |
                                             UIRemoteNotificationTypeAlert)
#endif
         // Required
         categories:nil];
    }
    
    [APService setupWithOption:launchOptions];
    
    //友盟登陆
    [[UMSocialManager defaultManager]openLog:NO];
    [[UMSocialManager defaultManager] setUmSocialAppkey:UMAppKey];
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:UMAppId appSecret:UMAppSecret redirectURL:nil];
    
    
    //友盟统计
//    [MobClick setCrashReportEnabled:YES]; // 如果不需要捕捉异常，注释掉此行
    [MobClick setLogEnabled:YES];  // 打开友盟sdk调试，注意Release发布时需要注释掉此行,减少io消耗
    [MobClick startWithAppkey:UMAppKey reportPolicy:BATCH   channelId:nil];
    NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    [MobClick setAppVersion:version];
    [MobClick updateOnlineConfig];  //在线参数配置
    [MobClick profileSignInWithPUID:kkUserDict[@"id"]];
    
//    [MobClick event:@"AppFirst"];
    return YES;
}
//分享回调
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url];
    if (!result) {
        // 其他如支付等SDK的回调
    }
    return result;
}

#pragma mark 连接融云服务器
- (void)conectRongYunServer{

    // 快速集成第二步，连接融云服务器
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    if ([defaults objectForKey:@"RongYunToken"]) {
        [[RCIM sharedRCIM] connectWithToken:[defaults objectForKey:@"RongYunToken"] success:^(NSString *userId) {
            // Connect 成功
//           NSLog(@"融云连接成功！== %@",userId);
            //存储链接状态
            [[NSNotificationCenter  defaultCenter] postNotificationName:@"rongYunConnectSuccess" object:nil];
            
        }error:^(RCConnectErrorCode status) {
            
            // Connect 失败
//            NSLog(@"融云连接失败！");
        }tokenIncorrect:^() {
            
//            NSLog(@"融云连接失败  Token 失效！");
            // Token 失效的状态处理
        }];
    }
    
    
}
- (void)onRCIMConnectionStatusChanged:(RCConnectionStatus)status
{
    
}
// 获取苹果推送权限成功。
-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    // 设置 deviceToken。
//    [[RCIM sharedRCIM] setDeviceToken:deviceToken];
    [APService registerDeviceToken:deviceToken];
}

-(void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    [APService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
     
//    NSLog(@"userInfo = %@",userInfo);
    
    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"notibool"]) {
        NSNotification *notification =[NSNotification notificationWithName:@"PresentView" object:nil userInfo:userInfo];
        [[NSNotificationCenter defaultCenter] postNotification:notification];

    }
   //    NSNotification *notification1 =[NSNotification notificationWithName:@"Notification" object:nil userInfo:userInfo];
    //通过通知中心发送通知
//   [[NSNotificationCenter defaultCenter] postNotification:notification1];
}
// 获取用户信息的方法。
-(void)getUserInfoWithUserId:(NSString *)userId completion:(void(^)(RCUserInfo* userInfo))completion
{
//    NSLog(@"userId ====%@, targetId ==== %@",userId,[[NSUserDefaults standardUserDefaults] objectForKey:@"mobile"]);
    
    // 此处最终代码逻辑实现需要您从本地缓存或服务器端获取用户信息。
    
      RCUserInfo *user = [[RCUserInfo alloc]init];
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"targetId"] isEqual: userId]) {
    
        user.userId = [[NSUserDefaults standardUserDefaults] objectForKey:@"targetId"];
        
        user.name = [[NSUserDefaults standardUserDefaults] objectForKey:@"useName"];
        
        user.portraitUri = [[NSUserDefaults standardUserDefaults] objectForKey:@"imgStr"];
//        NSLog(@"凤飞飞================== %@",user.portraitUri);

         return completion(user);
    }
   else if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"mobile"]isEqual: userId] ) {
        user.userId =  [[NSUserDefaults standardUserDefaults] objectForKey:@"realname"];
       user.name =  [[NSUserDefaults standardUserDefaults] objectForKey:@"mobile"];
       user.portraitUri =  [[NSUserDefaults standardUserDefaults] objectForKey:@"avatar"];
//       NSLog(@"================== %@",user.portraitUri);
         return completion(user);
    }
    
       return completion(nil);
}

- (void)getGroupInfoWithGroupId:(NSString *)groupId completion:(void (^)(RCGroup *))completion
{
    
}
- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    int unreadMsgCount = [[RCIMClient sharedRCIMClient] getUnreadCount:@[
                                                                         @(ConversationType_PRIVATE),
                                                                         @(ConversationType_DISCUSSION),
                                                                         @(ConversationType_APPSERVICE),
                                                                         @(ConversationType_PUBLICSERVICE),
                                                                         @(ConversationType_GROUP)
                                                                         ]];
    application.applicationIconBadgeNumber = unreadMsgCount;

}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"notibool"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.

    [APService resetBadge];
    application.applicationIconBadgeNumber = 0;
    

    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"notibool"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}



#pragma mark - Core Data stack

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

- (NSURL *)applicationDocumentsDirectory {
    // The directory the application uses to store the Core Data store file. This code uses a directory named "GuoYuPeng.DMGME" in the application's documents directory.
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

- (NSManagedObjectModel *)managedObjectModel {
    // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"DMGME" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
    // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it.
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }
    
    // Create the coordinator and store
    
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"DMGME.sqlite"];
    NSError *error = nil;
    NSString *failureReason = @"There was an error creating or loading the application's saved data.";
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        // Report any error we got.
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
        dict[NSLocalizedFailureReasonErrorKey] = failureReason;
        dict[NSUnderlyingErrorKey] = error;
        error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
        // Replace this with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
//        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
    
    return _persistentStoreCoordinator;
}


- (NSManagedObjectContext *)managedObjectContext {
    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }
    
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (!coordinator) {
        return nil;
    }
    _managedObjectContext = [[NSManagedObjectContext alloc] init];
    [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    return _managedObjectContext;
}

#pragma mark - Core Data Saving support

- (void)saveContext {
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        NSError *error = nil;
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
            // Replace this implementation with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
//            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
    }
}

@end
